package com.bb.blog.code.collection;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;

public class SomeMap<K, V> implements Map<K, V> {

    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;

    static final int MAXIMUM_CAPACITY = 1 << 30;

    static final float DEFAULT_LOAD_FACTOR = 0.75f;


    final float loadFactor;
    /* 实例字段 */
    transient Node<K, V>[] table;
    transient Set<Map.Entry<K, V>> entrySet;
    transient int size;
    /* 用于保护map在被遍历的时候没有修改和插入 */
    transient int modCount;
    int threshold;

    /**
     * 构造方法
     */
    public SomeMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            initialCapacity = DEFAULT_INITIAL_CAPACITY;
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            loadFactor = DEFAULT_LOAD_FACTOR;
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);

    }

    public SomeMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    public SomeMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
    }

    public SomeMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
//        putMapEntries(m, false);
    }


    /* 静态方法  */
    static int hash(Object key) {
        return key == null ? 0 : key.hashCode();
    }

    /* 从最大一位开始慢慢吧后面都变成1 最后再加1 得到大于cap的最小2的幂 */
    static int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
//        n |= n >>> 32;
        return (n < 0) ? 1 : (n > MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }

    static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c;
            Type[] ts, as;
            Type t;
            ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (Type t1 : ts) {
                    if (((t = t1) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType) t).getRawType() ==
                            Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
            ((Comparable) k).compareTo(x));
    }




    @Override
    public int size() {
        return this.size;
    }

    @Override
    public boolean isEmpty() {
        return this.size == 0;
    }

    @Override
    public boolean containsKey(Object key) {
        // todo
        return false;
    }

    @Override
    public boolean containsValue(Object value) {
        // todo
        return false;
    }

    @Override
    public V get(Object key) {
        int hash = hash(key);
        Node<K, V> node;
        return (node = getNode(hash, key)) == null ? null : node.value;
    }

    @Override
    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, false);
    }

    @Override
    public V remove(Object key) {
        int hash = hash(key);
        Node<K, V> node;
        return ((node = removeNode(hash, key)) == null) ? null : node.getValue();
    }

    @Override
    public void putAll(Map<? extends K, ? extends V> m) {

    }

    @Override
    public void clear() {

    }

    @Override
    public Set<K> keySet() {
        return null;
    }

    @Override
    public Collection<V> values() {
        return null;
    }

    @Override
    public Set<Entry<K, V>> entrySet() {
        return null;
    }

    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        Node<K, V>[] tab;
        Node<K, V> node;
        int n;
        int i;

        if ((tab = table) == null || (n = tab.length) == 0) {
            n = (tab = resize()).length;
        }
        if ((node = tab[i = (n - 1) & hash]) == null) {
            tab[i] = new Node<>(hash, key, value, null);

        } else {
            Node<K, V> existsNode;
            K k;
            // 如果是同一个key
            if (node.hash == hash && ((k = node.key) == key || (key != null && key.equals(k)))) {
                existsNode = node;
            } else {
                for (int binCount = 0; ; ++binCount) {
                    // 插入
                    if ((existsNode = node.next) == null) {
                        node.next = new Node<>(hash, key, value, null);
//                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
//                            treeifyBin(tab, hash);
                        break;
                    }
                    // 更新
                    if (existsNode.hash == hash &&
                        ((k = existsNode.key) == key || (key != null && key.equals(k))))
                        break;
                    node = existsNode;
                }
            }

            if (existsNode != null) {
                V oldValue = existsNode.value;
                if (!onlyIfAbsent || oldValue == null) {
                    existsNode.value = value;
                }
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        return null;

    }

    /*初始化 或者 倍化 table 的大小。如果*/
    private Node<K, V>[] resize() {
        Node<K, V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;

        int newCap, newThr = 0;
        if (oldCap > 0) { //已经有数据了
            if (oldCap >= MAXIMUM_CAPACITY) {  // 这个表已经很大了所以改变threshold不去触发resize()
                threshold = Integer.MAX_VALUE;
                return oldTab;
            } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) {
                newThr = oldThr << 1;
            }
        } else if (oldThr > 0) { // 没得数据或者刚初始化
            newCap = oldThr;
        } else { // 无参数的构造方法
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int) (DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }

        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        Node<K, V>[] newTab = (Node<K, V>[]) new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K, V> exestsNode;
                if ((exestsNode = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (exestsNode.next == null) { // 这个坑里只有一个Node，直接搬运
                        newTab[exestsNode.hash & (newCap - 1)] = exestsNode;
                    } else {
                        Node<K, V> loHead = null, loTail = null;
                        Node<K, V> hiHead = null, hiTail = null;
                        Node<K, V> next;
                        do {
                            next = exestsNode.next; // 找到下一个
                            /**
                             * 举个栗子：
                             * hash值用二进制表示是   XXXXAB; 其中每一位都是不确定的
                             *
                             * 原来容量是4   坑位i = hash & 3 ; 二进制: XXXXAB & 011
                             * 改变后容量是8 坑位i = hash & 7 ; 二进制: XXXXAB & 111
                             * & 按位与
                             * 在扩容前的坑位一致时说明 在循环中的existsNode AB值一致的
                             * 扩容后的位置只取决于高一位的数值是0还是1
                             * 所以用hash & 原来的容量 即 XXXXAB & 100 即可区分
                             *
                             */
                            if ((exestsNode.hash & oldCap) == 0) {  // 如果是0 原地不动
                                if (loTail == null)
                                    loHead = exestsNode;
                                else
                                    loTail.next = exestsNode;
                                loTail = exestsNode;
                            } else {  // 如果是1就去高位
                                if (hiTail == null)
                                    hiHead = exestsNode;
                                else
                                    hiTail.next = exestsNode;
                                hiTail = exestsNode;
                            }
                        } while ((exestsNode = next) != null);

                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

    final Node<K, V> getNode(int hash, Object key) {
        int i;
        K k;
        Node<K, V>[] tab;
        Node<K, V> first, e;
        if ((tab = table) != null && (i = tab.length) > 0 &&
            (e = tab[(i - 1) & hash]) != null) {
            do {
                if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                    return e;
            } while ((e = e.next) != null);

        }
        return null;
    }

    final Node<K, V> removeNode(int hash, Object key) {
        Node<K, V>[] tab;
        Node<K, V> p;
        int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) {
            Node<K, V> node = null;
            K k;

            do {
                if (p.hash == hash &&
                    ((k = p.key) == key ||
                        (key != null && key.equals(k)))) {
                    node = p;
                    break;
                }
            } while ((p = p.next) != null);

            if (node != null) {
                if (node == p)
                    tab[index] = node.next;
                else
                    p.next = node.next;
                ++modCount;
                --size;
                return node;
            }

        }
        return null;
    }

    /**
     * 节点类
     */
    static class Node<K, V> implements Map.Entry<K, V> {
        final int hash;
        K key;
        V value;
        Node<K, V> next;

        Node(int hash, K key, V value, Node<K, V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        @Override
        public K getKey() {
            return this.key;
        }

        @Override
        public V getValue() {
            return this.value;
        }

        @Override
        public V setValue(V value) {
            V oldValue = this.value;
            this.value = value;
            return oldValue;
        }

        @Override
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        @Override
        public final boolean equals(Object o) {
            if (o == this) {
                return true;
            }
            if (o instanceof Map.Entry) {
                Map.Entry<?, ?> e = (Entry<?, ?>) o;
                return Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue());
            }
            return false;
        }

        @Override
        public String toString() {
            return key + ":" + value;
        }
    }

    /**
     * 假设一开始是 8
     */

    static float p(int n, int max, HashMap<Integer, Float> resultMap){
        if(n == 0){
            return 0;
        }
        if(resultMap.containsKey(n)){
            return resultMap.get(n);
        }
        float used = 0;
        for (int i = 0; i < n; i++) {
            used += (1-p(i,max,resultMap));
        }
        float res;
        resultMap.put(n, res=(used/max));
        return res;
    }

    public static void main(String[] args) {
        HashMap<String,String> hashMap = new HashMap<>(3);
        for (int i = 0; i < 10; i++) {
            hashMap.put("" +i,""+i);
        }



    }
}
